package com.nowcoder.community.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author AnYang
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/1/17
 */
@Component
public class MailClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(MailClient.class);

    // 主要的核心类
    @Autowired
    private JavaMailSender javaMailSender;

    // 因为是在服务器端，每次发送只会给一个人发，所以直接注入配置文件中的username即可
    @Value("${spring.mail.username}")
    private String from;

    // to:要发送给谁；subject：发送邮件标题；content：内容
    public void sendMail(String to, String subject, String content) {
        //构建JavaMailSender中的MimeMessage，调用JavaMailSender的send方法即可实现发送
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            // true，允许支持html; 为false，就是普通文本文字
            helper.setText(content, true);
            javaMailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            LOGGER.error("发送邮件失败" + e.getMessage());
        }
    }
}
